#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define BUF_SIZE 4096


void send_ota_file(int client_sock, const char *filename) {
    printf("[INFO] 客户端请求OTA文件: %s\n", filename);
    FILE *fp = fopen(filename, "rb");
    if (!fp) {
        const char *not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
        send(client_sock, not_found, strlen(not_found), 0);
        return;
    }
    fseek(fp, 0, SEEK_END);
    long filesize = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char header[512];
    int header_len = snprintf(header, sizeof(header),
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: application/octet-stream\r\n"
        "Content-Length: %ld\r\n"
        "Content-Disposition: attachment; filename=\"ota.bin\"\r\n"
        "Connection: close\r\n\r\n", filesize);
    send(client_sock, header, header_len, 0);

    char buf[4096];
    int n, total = 0;
    while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
        send(client_sock, buf, n, 0);
        total += n;
    }
    fclose(fp);
    printf("[INFO] 已发送OTA文件，总字节数: %d\n", total);
}
int main() {
    int server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock < 0) {
        perror("[ERROR] 创建socket失败");
        exit(1);
    }
    printf("[INFO] Socket创建成功，fd=%d\n", server_sock);

    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(PORT);

    if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("[ERROR] 绑定端口失败");
        exit(1);
    }
    printf("[INFO] 绑定端口 %d 成功\n", PORT);

    if (listen(server_sock, 5) < 0) {
        perror("[ERROR] listen失败");
        exit(1);
    }
    printf("OTA HTTP服务器已启动，端口%d\n", PORT);

    while (1) {
        printf("[INFO] 等待客户端连接...\n");
        int client_sock = accept(server_sock, NULL, NULL);
        if (client_sock < 0) {
            perror("[ERROR] accept失败");
            continue;
        }
        printf("[INFO] 客户端已连接，fd=%d\n", client_sock);

        char buffer[1024] = {0};
        int recv_len = recv(client_sock, buffer, sizeof(buffer)-1, 0);
        if (recv_len > 0) {
            buffer[recv_len] = '\0';
            printf("[INFO] 收到请求:\n%s\n", buffer);
            if (strstr(buffer, "GET /bin/ota.bin") != NULL || strstr(buffer, "GET //bin/ota.bin") != NULL) {
                send_ota_file(client_sock, "bin/ota.bin");
            } else {
                printf("[WARN] 未知请求，返回404\n");
                const char *not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
                send(client_sock, not_found, strlen(not_found), 0);
            }
        } else {
            printf("[WARN] 未收到有效请求\n");
        }
        close(client_sock);
        printf("[INFO] 客户端连接已关闭\n");
    }
    close(server_sock);
    return 0;
}